//
//  KBUserAccount.swift
//  KimboWeiBoSwift
//
//  Created by kimbo on 15/12/19.
//  Copyright © 2015年 kimbo. All rights reserved.
//

import UIKit

class KBUserAccount: NSObject, NSCoding {

    // MARK: - 属性
    /// 用户是否登录过
    class var userLogin: Bool {
        //计算性属性中,只有get可以省略
        return KBUserAccount.loadUserAccount() != nil
    }
    
    /// AccessToken
    var access_token: String?
    
    /// 当前授权用户的UID
    var uid: String?
    
    /// access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0 {
        didSet {
            //自己生成过期时间
            expires_Date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 过期时间
    var expires_Date: NSDate?
    
    /// 用户昵称
    var screen_name: String?
    
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    // MARK: - 方法
    init(dict: [String: AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        // 解决如果键值不匹配,就报错问题
    }
    
    /// 归档
    func encodeWithCoder(aCoder: NSCoder) {
        //告诉需要归档那些对象
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    /// 反归档
    required init?(coder aDecoder: NSCoder) {
        //告诉反归档那些对象,并为属性赋值
        super.init()
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    /// 沙盒路径
    static let filePath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
    
    /// 保存UserAccount到沙盒
    func saveUserAccount() {
        
        //注：对象方法里访问static属性需要加类名
        NSKeyedArchiver.archiveRootObject(self, toFile: KBUserAccount.filePath)
    }
    
    // 此方法调用频繁,会消耗性能,优化成优先从缓存中取
    /// 代表缓存中的userAccounts
    static var userAccount: KBUserAccount?
    /// 从沙盒读取UserAccount(优先从缓存中取)
    class func loadUserAccount() -> KBUserAccount? {
        //先去缓存中找
        if userAccount == nil {
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? KBUserAccount
        }
        
        //userAccount不一定有,并且如果对象有了、时间没有过期才算有效的userAccount
        if userAccount != nil && userAccount?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            
            return userAccount!
        }
        
        //来到这里要么没帐号，要么过了期
        return nil
    }
    
    /// 加载用户信息
    func loadUserInfo(finished: (error: NSError?) -> ()) {
        KBNetWorkTool.sharedInstance.loadUserInfo { (result, error) -> () in
            // 判断网络请求是否出错
            if result == nil || error != nil {
                finished(error: error)
                return
            }
            
            //没出错,更新userAccount
            self.screen_name = result!["screen_name"] as? String
            
            self.avatar_large = result!["avatar_large"] as? String
            
            //保存到沙盒
            self.saveUserAccount()
            //更新缓存中userAccount
            KBUserAccount.userAccount = self
            
            finished(error: nil)
        }
    }
    
}




